package com.airnews.ticket.ui.flight;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.airnews.ticket.FlyApplication;
import com.airnews.ticket.R;
import com.airnews.ticket.model.CabinItem;
import com.airnews.ticket.model.FlightInfo;
import com.airnews.ticket.model.FlightOrder;
import com.airnews.ticket.model.FlightRestrict;
import com.airnews.ticket.model.OrderInfo;
import com.airnews.ticket.model.OrderInfoResult;
import com.airnews.ticket.model.SearchOrder;
import com.airnews.ticket.model.TotalOrderInfoResult;
import com.airnews.ticket.net.WebAccessor;
import com.airnews.ticket.pay.util.BaseHelper;
import com.airnews.ticket.ui.BaseActivity;
import com.airnews.ticket.ui.order.OrderList;
import com.airnews.ticket.util.AddrUtil;
import com.airnews.ticket.util.DateUtil;
import com.airnews.ticket.util.FlyUtil;
import com.airnews.ticket.util.Utils;
import com.mobclick.android.MobclickAgent;

public class FlyOrderSave extends BaseActivity implements OnClickListener {
	public final int SEARCH_ERROR=7;
	public final static int SUCCESS = 0;
	public final static int FAIL = 1;
	public final static int CANCEL_SUCCESS = 2;
	public final static int ABOLISH_SUCCESS = 3;
	public final static int RETURN_AMOUNT_SUCCESS = 4;
	public final static int APPLY_FOR_REFUND_SUCCESS = 5;
	public final static int MODIFY_NO_SUCCESS = 6;
	public final static int CHANGEDATE_SUCCESS = 7;
	
	public  final int DATE_DIALOG_ID = 11;
	public  final int TIME_DIALOG_ID = 12;
	public  final int REFUNDTYPE_DIALOG_LIST = 10;
	
	public static OrderInfo ORDER_INFO;
	public static FlightOrder ORDER_DETAIL;
	public static FlightInfo flight;
	public static FlightInfo returnFlight;
	public static List<Map<String,String>> passengerList = new ArrayList<Map<String,String>>();
	public static List<Map<String,String>> contactList = new ArrayList<Map<String,String>>();
	public static List<Map<String,String>> itineraryList = new ArrayList<Map<String,String>>();
	public static String OrderNo;
	public static String[] FlightOrderNO;
	
	public float sumPriceV;
	
	public SimpleAdapter passenger_sa,contactor_sa,itinerary_sa,mileager_sa;
	public ListView lv_passenger,lv_contactor,lv_itinerary,lv_mileager;
	
	//退改签政策
	private RelativeLayout flightDetailRestrict,ticketOrderNo_layout;
	private boolean isOpenRestrict = true;
	private TextView restrict;
	private ImageView restrictArrow;
	private String restrictValue;
	private FlightRestrict flightRestrict;
	
	private ProgressDialog progressDialog = null;
	
	TextView departureDate, departureWeek, flightNo,
		order_status, order_no, order_date,totalAmount,
		ticketOrderNo,passengerName,course,
		ticketOrder_date,tripType,rebate,ticket_status,
		
		fromCity, flight_depart, fromtime, fromaf, 
		toCity, flight_arrive, totime, toaf, 
		airc, baseCabin, food, stopNo, flight_price_title2, cabinPrice, discount, price, basePrice, fuelTax,
		airc0, others, airc1, airc2,
		
		consigneeName,consigneePhone,consigneeAddress,itineraryNo,
		passenger_name, passenger_id_number,
		contactor_name, contactor_mobile,
		sumPrice;
	private LinearLayout itinerary_info_sum_layout;
	private AddrUtil addrUtil;
	
	private FlyUtil flyUtil;
	
	//后退回列表页时使用
	public static List<OrderInfo> orderist = new ArrayList<OrderInfo> ();
	
	private Toast toast;
	
	private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour = 0;
    private int mMinute = 0;
    private String newDateStr;
    private TextView newDate;

	public static String isItinerary;//是否需要行程单
	public static String isInsurance = "0";//是否需要保险
	//保险、行程单价格
	private TextView insurance_shuomin,itinerary_price;
	private float insuranceShuominPrice,itineraryPrice;
	
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.fly_order_save);
		activityList.add(this);
		
		renderPassData();
		renderContactData();
		renderItineraryData();
		
		insurance_shuomin = (TextView) findViewById(R.id.insurance_shuomin);
		itinerary_price = (TextView) findViewById(R.id.itinerary_price);
		
		//初始化接钮
		findViewById(R.id.btn_pay).setOnClickListener(this);
		findViewById(R.id.btn_cancel).setOnClickListener(this);
		findViewById(R.id.backBut).setOnClickListener(this);
		findViewById(R.id.btn_refundment).setOnClickListener(this);
		findViewById(R.id.btn_bounce_ticket).setOnClickListener(this);
		findViewById(R.id.btn_abolish_ticket).setOnClickListener(this);
		findViewById(R.id.btn_modifyPassengerIDNo).setOnClickListener(this);
		findViewById(R.id.btn_change_date).setOnClickListener(this);
		//初始化地址参数
		addrUtil = new AddrUtil(this);
		//初始化航空参数
		flyUtil = new FlyUtil(this);

		
		//总订单信息
		order_status = (TextView) findViewById(R.id.order_status);
		order_no = (TextView) findViewById(R.id.order_no);
		order_date = (TextView) findViewById(R.id.order_date);
		totalAmount =  (TextView) findViewById(R.id.totalAmount);
		
		
		passengerName =  (TextView) findViewById(R.id.passengerName); 
		ticketOrderNo =  (TextView) findViewById(R.id.ticketOrderNo); 
		course =  (TextView) findViewById(R.id.course); 
		ticketOrder_date =  (TextView) findViewById(R.id.ticketOrder_date); 
		tripType =  (TextView) findViewById(R.id.tripType); 
		rebate =  (TextView) findViewById(R.id.rebate); 
		ticket_status =  (TextView) findViewById(R.id.ticket_status); 
		
		fromCity = (TextView) findViewById(R.id.fromCity); 
		flight_depart = (TextView) findViewById(R.id.flight_depart); 
		fromtime = (TextView) findViewById(R.id.fromtime);  
		fromaf = (TextView) findViewById(R.id.fromaf);  
		toCity = (TextView) findViewById(R.id.toCity);
		flight_arrive = (TextView) findViewById(R.id.flight_arrive);
		totime = (TextView) findViewById(R.id.totime);
		toaf = (TextView) findViewById(R.id.toaf);
		airc = (TextView) findViewById(R.id.airc);
		baseCabin = (TextView) findViewById(R.id.baseCabin);
		food = (TextView) findViewById(R.id.food);
		stopNo = (TextView) findViewById(R.id.stopNo);
		flight_price_title2 = (TextView) findViewById(R.id.flight_price_title2);
		cabinPrice = (TextView) findViewById(R.id.cabinPrice);
		discount = (TextView) findViewById(R.id.discount);
		price = (TextView) findViewById(R.id.price);
		basePrice = (TextView) findViewById(R.id.basePrice);
		fuelTax = (TextView) findViewById(R.id.fuelTax);
		airc0 = (TextView) findViewById(R.id.airc0);
		others = (TextView) findViewById(R.id.others);
		airc1 = (TextView) findViewById(R.id.airc1);
		airc2 = (TextView) findViewById(R.id.airc2);
		
		itinerary_info_sum_layout = (LinearLayout) findViewById(R.id.itinerary_info_sum_layout);
		ticketOrderNo_layout = (RelativeLayout) findViewById(R.id.ticketOrderNo_layout);
		
		consigneeName = (TextView) findViewById(R.id.consigneeName);
		consigneePhone = (TextView) findViewById(R.id.consigneePhone);
		consigneeAddress = (TextView) findViewById(R.id.consigneeAddress);
		itineraryNo = (TextView) findViewById(R.id.itineraryNo);
		
		passenger_name = (TextView) findViewById(R.id.passenger_name);
		passenger_id_number = (TextView) findViewById(R.id.passenger_id_number);
		contactor_name = (TextView) findViewById(R.id.contactor_name);
		contactor_mobile = (TextView) findViewById(R.id.contactor_mobile);
		sumPrice = (TextView) findViewById(R.id.sumPrice);
		
		renderData();
		
		//退改签
		flightDetailRestrict = (RelativeLayout) findViewById(R.id.flight_detail_restrict);
		flightDetailRestrict.setOnClickListener(this);
		restrict = (TextView) findViewById(R.id.restrict);
		restrictArrow = (ImageView) findViewById(R.id.restrictArrow);
		
		//得到当前日期
        final Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
		
	}
	
	private void renderPassData(){
		//登机人
		passenger_sa = new SimpleAdapter(
				this,
				passengerList,
				R.layout.flight_passenger_item,
				new String[] { "passengerName", "passengerIdNumber"},
				new int[] { R.id.passenger_name, R.id.passenger_id_number});
		lv_passenger = (ListView) findViewById(R.id.passenger_list);
		lv_passenger.setDivider(null);
		lv_passenger.setAdapter(passenger_sa);
		Utils.setListViewHeightBasedOnChildren(lv_passenger);//更新list高度
	}
	
	private void renderContactData() {
		//联系人
		contactor_sa = new SimpleAdapter(
				this,
				contactList,
				R.layout.flight_contactor_item,
				new String[] { "contactName", "phone"},
				new int[] { R.id.contactor_name, R.id.contactor_mobile});
		lv_contactor = (ListView) findViewById(R.id.contactor_list);
		lv_contactor.setDivider(null);
		lv_contactor.setAdapter(contactor_sa);
		Utils.setListViewHeightBasedOnChildren(lv_contactor);
	}

	private void renderItineraryData(){
		//收件人
		itinerary_sa = new SimpleAdapter(
				this,
				itineraryList,
				R.layout.flight_itinerary_item,
				new String[] { "consigneeName", "consigneePhone","consigneeAddress"},
				new int[] { R.id.consigneeName, R.id.consigneePhone, R.id.consigneeAddress});
		lv_itinerary = (ListView) findViewById(R.id.itinerary_list);
		lv_itinerary.setDivider(null);
		lv_itinerary.setAdapter(itinerary_sa);
	}
	
	//初始化数据
	private void renderData() {
		//TODO： 再次查找数据
		
		String departureTime=flight.departureTime;
		if(departureTime!=null&&departureTime.length()>=10){
			departureTime = departureTime.substring(0,10);
		}
		
		String departureCity = addrUtil.getCityByCode(flight.departure).getCity();
		String arrivalCity = addrUtil.getCityByCode(flight.arrival).getCity();
		flight.departureTime = departureTime;
		System.out.println("flight.departure="+flight.departure);
		System.out.println("flight.arrival="+flight.arrival);
		System.out.println("flight.airline="+flight.airline);
		System.out.println("flight.departureTime="+flight.departureTime);
		System.out.println("flight.cabinFlight="+flight.cabinFlight);
		
		course.setText(flyUtil.getName(flight.airline.substring(0, 2)) + "  " + departureCity + "->" + arrivalCity);
		ticketOrder_date.setText(departureTime);
		airc.setText(flight.flightNo);
		
		order_status.setText(flyUtil.orderStatusMap.get("0"));
		order_no.setText(OrderNo);
		order_date.setText("");
		System.out.println("isItinerary="+isItinerary);
	    if("2".equals(isItinerary)){
	    	LinearLayout itineraryLayout = (LinearLayout) findViewById(R.id.flight_itinerary);
	    	itineraryLayout.setVisibility(View.VISIBLE);
	    	renderItineraryData();
	    	itineraryPrice = 5.0f;
	    } else {
	    	itineraryPrice = 0.0f;
	    }
	    itinerary_price.setText("￥" + itineraryPrice + "元");
	    
		List<CabinItem> cabinlist = flight.cabinItems;
		if(cabinlist!=null&&cabinlist.size()>0){
        	CabinItem cabinItem= cabinlist.get(0);//cabinlist.size()-1
    		
    		if(cabinItem.ticketNO != null && !cabinItem.ticketNO.equals("")){
    			ticketOrderNo.setText(cabinItem.ticketNO);
    		} else {
    			ticketOrderNo_layout.setVisibility(View.GONE);
    		}
    		ticket_status.setText(flyUtil.orderStatusMap.get("0"));
//    		tripType.setText(flyUtil.getTripTypeCode(Integer.valueOf(cabinItem.tripType)));
    		baseCabin.setText(FlyUtil.getJClassName(cabinItem.baseCabin) + " " + cabinItem.baseCabin);
    		
    		flight_price_title2.setText("");
    		
    		
			String priceFormat = cabinItem.price.indexOf(".00") != -1 ? cabinItem.price.substring(0, cabinItem.price.indexOf(".00")) : cabinItem.price;
        	String ibePaymentFormat = cabinItem.ibePayment.indexOf(".00") != -1 ? cabinItem.ibePayment.substring(0, cabinItem.ibePayment.indexOf(".00")) : cabinItem.ibePayment;
        	String cabinPriceFormat = cabinItem.cabinPrice.indexOf(".00") != -1 ? cabinItem.cabinPrice.substring(0, cabinItem.cabinPrice.indexOf(".00")) : cabinItem.cabinPrice;
        	Float priceCal = Float.parseFloat(cabinPriceFormat) - Float.parseFloat(ibePaymentFormat);
        	
			cabinPrice.setText("票价:" +cabinPriceFormat + "元" + "("+FlyUtil.parseDiscount(cabinItem.discount)+")");
			price.setText("  净价:" + String.valueOf(priceCal)  + "元");
			rebate.setText("返利：" + ibePaymentFormat + "元");
			
			((TextView) findViewById(R.id.flight_ticket_type)).setText(cabinItem.ticketType);
			
			String airportTaxV = (cabinItem.airportTax.equals("") ||  (cabinItem.airportTax == null) ? "0" : cabinItem.airportTax) ;
			String fuelTaxV = (cabinItem.fuelTax.equals("") || (cabinItem.fuelTax == null) ? "0" : cabinItem.fuelTax);
			fuelTax.setText("￥" + airportTaxV + "/￥" + fuelTaxV );
			
			sumPriceV = Float.valueOf(priceCal) + Float.valueOf(airportTaxV) + Float.valueOf(fuelTaxV);
			
			if(isInsurance.equals("0")){
				insuranceShuominPrice = 20.0f * passengerList.size();
			} else {
				insuranceShuominPrice = 0;
			}
			insurance_shuomin.setText("￥" + insuranceShuominPrice + "元");
			
		    
			sumPriceV = sumPriceV + insuranceShuominPrice + itineraryPrice;
	       	totalAmount.setText("￥" + sumPriceV + "元");
	       	sumPrice.setText("￥" + sumPriceV + "元");
		}
	    
		findViewById(R.id.btn_pay).setVisibility(View.VISIBLE);
		findViewById(R.id.btn_cancel).setVisibility(View.VISIBLE);
	}
	
	
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_pay: {
			//付款
			TotalOrderInfoResult orderResult = new TotalOrderInfoResult();
			orderResult.OrderNO = OrderNo;
			orderResult.FlightOrderNO = FlightOrderNO;
			
			//跳转到信用卡支付页面
			Intent intent = new Intent();
			intent.setClass(FlyOrderSave.this, CreditCard.class);
			CreditCard.totalOrderInfoResult = orderResult;
			CreditCard.sumPriceFormat = String.valueOf(sumPriceV);
			CreditCard.isNowPay = true;
			CreditCard.flight = flight;
			CreditCard.returnFlight = returnFlight;
			CreditCard.passengerList = passengerList;
			CreditCard.contactList = contactList;
			CreditCard.isInsurance = isInsurance;
			CreditCard.isItinerary = isItinerary;
			CreditCard.itineraryList = itineraryList;
			startActivity(intent);
			break;
		}
		case R.id.btn_cancel: {
			//取消订单
			Log.i("FlyOrderSave", "btn_cancel");
			progressDialog = ProgressDialog.show(this, "请稍等...", "正在取消订单中...",true);
			final Thread thread1 = new Thread() {
				public void run() {
					OrderInfoResult orderResult = WebAccessor.applyForCountermand(FlyOrderSave.this, OrderNo);
					if (progressDialog.isShowing()) {
						if (orderResult== null) {
							Message msg = new Message();
							msg.what = FAIL;
							msg.obj = "取消订单操作失败";
							myHandler.sendMessage(msg);
						}else if(!"0".equals(orderResult.Ret_Code)){
							Message msg = new Message();
							msg.what = FAIL;
							msg.obj = orderResult.Ret_Msg;
							myHandler.sendMessage(msg);
						}else{
							Message msg = new Message();
							msg.what = CANCEL_SUCCESS;
							myHandler.sendMessage(msg);
							//更新页面状态
//							ticket_status.setText(flyUtil.orderStatusMap.get(ORDER_DETAIL.Status));
						}
						progressDialog.dismiss();
					}
				}
			};
			progressDialog.setCancelable(true);
			thread1.start();
			break;
		}
		case R.id.backBut: {
			Intent intent = new Intent(FlyOrderSave.this, OrderList.class);
			OrderList.UPDATE_INDICATOR = true;
			startActivity(intent);
			
			break;
		}
		case R.id.flight_detail_restrict:
			if(isOpenRestrict){
				String detailRestrict = ((FlyApplication)getApplication()).getPolicyRule();
				if(detailRestrict == null){
					getFlightRestrict();
				}
				isOpenRestrict = false;
			} else {
				restrict.setText("点击查看详细...");
				restrictArrow.setVisibility(View.GONE);
				isOpenRestrict = true;
			}
			
			break;
			
		}
		
		
	}

	//处理
	Handler myHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCESS:
				toast = Toast.makeText(FlyOrderSave.this, "操作成功", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				break;
			case FAIL:
				BaseHelper.showDialog(FlyOrderSave.this, "提示", (String)msg.obj,
						R.drawable.infoicon);
				break;
			case CANCEL_SUCCESS:
				toast = Toast.makeText(FlyOrderSave.this, "取消订单成功", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				//更新页面状态
				Intent intent1 = new Intent(FlyOrderSave.this, OrderList.class);
				OrderList.orderist.clear();
				SearchOrder searchOrder1 = new SearchOrder();
				searchOrder1.OrderNo = ORDER_DETAIL.TicketOrderNo;
				OrderList.searchOrder = searchOrder1;
    			startActivity(intent1);
				break;
				
			}
			super.handleMessage(msg);
		}
	};
	
	
	private void getFlightRestrict() {
		progressDialog = ProgressDialog.show(this, "请稍等...", "查询退改签明细...",true);
		final Thread thread = new Thread() {
			public void run() {
				flightRestrict =  WebAccessor.getFlightRestrict(FlyOrderSave.this,flight);
				if (progressDialog.isShowing()) {
					if (flightRestrict!= null) {
						Message msg = new Message();
						msg.what = SUCCESS;
						restrictHandler.sendMessage(msg);
					} else {
						Message msg = new Message();
						msg.what = SEARCH_ERROR;
						msg.obj = "无法查询到退改签明细";
						restrictHandler.sendMessage(msg);
					}
					progressDialog.dismiss();
				}
			}
		};
		progressDialog.setCancelable(true);
		thread.start();
	}
	
	public Handler restrictHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SEARCH_ERROR:
				Toast.makeText(FlyOrderSave.this, (String)msg.obj, Toast.LENGTH_LONG).show();
				break;
			case SUCCESS:
				restrictValue = flightRestrict.airc0;
				//退订票规则
				System.out.println("restrictValue="+restrictValue);
				restrict.setText(restrictValue);
				restrictArrow.setVisibility(View.GONE);
				break;
			}
		}
	};
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		    case DATE_DIALOG_ID:
		    	return new DatePickerDialog(this, dsl, mYear, mMonth, mDay);
		    case TIME_DIALOG_ID:
		    	return new TimePickerDialog(this, ts1,mHour,mMinute,true);
		default:
			return null;
		}
	}
	
	
    //准备日期设置监听器
    private OnDateSetListener dsl = new DatePickerDialog.OnDateSetListener(){

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear =year;
			mMonth= monthOfYear;
			mDay= dayOfMonth;
			newDateStr = mYear+"-"+DateUtil.pad(mMonth+1)+"-"+DateUtil.pad(mDay);
			newDate.setText(newDateStr);
		}
    };
    
    private OnTimeSetListener ts1 = new OnTimeSetListener(){

		public void onTimeSet(TimePicker arg0, int hour, int minute) {
			// TODO Auto-generated method stub
			mHour = hour;
			mMinute = minute;
			newDateStr = mYear+"-"+DateUtil.pad(mMonth+1)+"-"+DateUtil.pad(mDay) + " " + DateUtil.pad(mHour) + ":" + DateUtil.pad(mMinute);
			System.out.println("format newDateStr = " + newDateStr);
			newDate.setText(newDateStr);
		}
    	
    };

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
			Intent intentDirectOut = new Intent();
			intentDirectOut.setClass(FlyOrderSave.this, FlyOrderDetail.class);
			System.out.println("onKeyDown flight = " + flight.airline);
			System.out.println("onKeyDown departure = " + addrUtil.getCityByCode(flight.departure).getCity());
			FlyOrderDetail.flight = flight;
			FlyOrderDetail.returnFlight = returnFlight;
			FlyOrderDetail.passengerList = passengerList;
			FlyOrderDetail.contactList = contactList;
			FlyOrderDetail.isItinerary = isItinerary;
			FlyOrderDetail.isInsurance = isInsurance;
			FlyOrderDetail.itineraryList = itineraryList;
			startActivity(intentDirectOut);
			
			return true;
		}
		return super.onKeyDown(keyCode, event);
	} 
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	} 
}
